/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package org.biubiu0002.baiblog.core.component;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.biubiu0002.baiblog.common.exception.BaiBlogException;
import org.biubiu0002.baiblog.common.exception.BizCodeEnumException;
import org.biubiu0002.baiblog.common.utils.R;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 异常处理器
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {IllegalArgumentException.class})
    public R handleIllegalException(IllegalArgumentException e){
        R r = new R();
        r.put("errorCode", BizCodeEnumException.ILLEGAL_INPUT_EXCEPTION.getCode());
        r.put("errorMsg", StringUtils.isNotBlank(e.getMessage())?e.getMessage():BizCodeEnumException.ILLEGAL_INPUT_EXCEPTION.getMsg());
        return r;
    }




    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e){
        log.error(e.getMessage(), e);
        return R.error(BizCodeEnumException.DB_DUPLICATE_KEY_EXCEPTION);
    }


    @ExceptionHandler(NoHandlerFoundException.class)
    public R handlerNoFoundException(NoHandlerFoundException e) {
        log.error(e.getMessage(), e);
        return R.error(BizCodeEnumException.HANDLER_NOT_FOUND_EXCEPTION);
    }

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(value = {BaiBlogException.class})
	public R handleRRException(BaiBlogException e){
		R r = new R();
		r.put("errorCode", e.getErrorCode());
		r.put("errorMsg", e.getErrorMsg());
		return r;
	}

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R handleJsonParseException(HttpMessageNotReadableException e){
        return R.error(BizCodeEnumException.INPUT_FORMAT_EXCEPTION.getCode(),e.getMessage());
    }


	@ExceptionHandler( Exception.class )
	public R handleException(Exception e){
	    if(e instanceof BaiBlogException){
            return R.error(((BaiBlogException) e).getErrorCode(),((BaiBlogException) e).getErrorMsg());
        }
	    else{
            log.error(e.getMessage(),e);
            return R.error(BizCodeEnumException.UNKNOWN_SERVER_EXCEPTION);
        }
	}
}
